package com.example.nophase.activity.staff;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;

import com.example.nophase.R;
import com.example.nophase.activity.FlowRecordActivity;
import com.example.nophase.adapter.ApplyForFromProjectListAdapter;
import com.example.nophase.api.RequstCommonApi;
import com.example.nophase.base.BaseActivity;
import com.example.nophase.common.BaseCallBack;
import com.example.nophase.common.BaseResp;
import com.example.nophase.common.LoginManager;
import com.example.nophase.custom.CustomDialog;
import com.example.nophase.custom.MoneyDialog;
import com.example.nophase.custom.TextFieldDialog;
import com.example.nophase.entity.AdultMsgDTO;
import com.example.nophase.entity.ProjectDTO;
import com.example.nophase.entity.ProjectDetailDTO;
import com.example.nophase.entity.SysUserVO;
import com.example.nophase.utils.HttpUtils;
import com.example.nophase.utils.WaterMarkBg;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

public class TaskFromActivity extends BaseActivity {


    @BindView(R.id.toolbar_btn)
    Button toolbarBtn;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.applyfor_no)
    TextView applyforNo;
    @BindView(R.id.applyfor_name)
    TextView applyforName;
    @BindView(R.id.applyfor_tel)
    TextView applyforTel;
    @BindView(R.id.applyfor_position_iv)
    ImageView applyforPositionIv;
    @BindView(R.id.applyfor_sumMoney)
    TextView applyforSumMoney;//本次申请
    @BindView(R.id.applyfor_totalMoney)
    TextView applyforTotalMoney;//累计金额
    @BindView(R.id.applyfor_limitMoney)
    TextView applyforLimitMoney;//年初限额
    @BindView(R.id.applyfor_resignMoney)
    TextView applyforResignMoney;//本次批付
    @BindView(R.id.applyfor_project_list)
    ListView applyforProjectList;
    @BindView(R.id.applyfor_from_progressbar)
    ProgressBar applyforFromProgressbar;
    @BindView(R.id.applyfor_save_btn)
    Button applyforSaveBtn;
    @BindView(R.id.content_layout)
    LinearLayout contentLayout;
    @BindView(R.id.applyfor_moneyAdd)
    TextView applyforMoneyAdd;
    private String forkey;
    private AdultMsgDTO applyForDTO;
    private List<ProjectDetailDTO> projectList;
    private ApplyForFromProjectListAdapter adapter;
    private int applyMoney;
    private int adultMoney;
    private boolean flag = false;
    private String invoice;
    private String cause;
    private String activityName;
    private String appType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_from);
        ButterKnife.bind(this);
        initData();
        setToolbar();

        toolbarBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String processInstanceId = applyForDTO.getProcessInstanceId();
                Intent intent = new Intent(TaskFromActivity.this, FlowRecordActivity.class);
                intent.putExtra("activityname", activityName);
                intent.putExtra("appType", appType);
                intent.putExtra("processInstanceId", processInstanceId);
                startActivity(intent);
            }
        });

        SysUserVO sysUserVO = LoginManager.getUserInfo(TaskFromActivity.this);
        String position = sysUserVO.getMoreInfo().getPosition();
        if (position.equals("区域业务员")) {
            applyforPositionIv.setBackgroundResource(R.drawable.qyyg);
        } else {
            if (position.equals("区域项目负责人")) {
                applyforPositionIv.setBackgroundResource(R.drawable.qyfzr);
            } else {
                applyforPositionIv.setBackgroundResource(R.drawable.znbmyg);
            }

        }

        List<String> labels = new ArrayList<>();
        labels.add(sysUserVO.getUsername());
        contentLayout.setBackground(new WaterMarkBg(TaskFromActivity.this, labels, -30, 18));
    }

    private void initData() {
        Intent intent = getIntent();
        forkey = intent.getStringExtra("forkey");
        System.out.println("forkey=======" + forkey);
        HttpUtils.getInstance().setAuthToken(LoginManager.getToken(this));
        applyforFromProgressbar.setVisibility(View.VISIBLE);
        Call<BaseResp<AdultMsgDTO<ProjectDetailDTO>>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadTaskFrom("ANDROID", Integer.valueOf(forkey));
        call.enqueue(new BaseCallBack<BaseResp<AdultMsgDTO<ProjectDetailDTO>>>() {
            @Override
            public void onSuccess(Response<BaseResp<AdultMsgDTO<ProjectDetailDTO>>> response) {
                applyforFromProgressbar.setVisibility(View.GONE);
                applyForDTO = response.body().getData();
                applyMoney = applyForDTO.getAppMoney().intValue();
                adultMoney = applyForDTO.getAuditMoney().intValue();
                projectList = applyForDTO.getTyBusinessAppDetailVos();
                applyforName.setText(applyForDTO.getAppUserName());

                activityName = applyForDTO.getActivitiname();
                appType = applyForDTO.getAppType();
                applyforTel.setText(applyForDTO.getAppUsertel());
                applyforNo.setText(applyForDTO.getNo().toString());
                applyforTotalMoney.setText(getdivide(applyForDTO.getTotalMoney()));
                applyforLimitMoney.setText(getdivide(applyForDTO.getLimitMoney()));
                applyforMoneyAdd.setText(getdivide(applyForDTO.getMoneyAdd()));
                applyforSumMoney.setText(String.valueOf(applyForDTO.getAppMoney()));
                ProjectDetailDTO item = (ProjectDetailDTO) applyForDTO.getTyBusinessAppDetailVos().get(0);
                cause = item.getAppReason();
                applyforResignMoney.setText("0");
                adapter = new ApplyForFromProjectListAdapter(projectList, TaskFromActivity.this);
                applyforProjectList.setAdapter(adapter);
                applyforProjectList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        showMoneyInputDialog(position);
                    }
                });

            }

            @Override
            public void onFailure(String message) {

            }
        });


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showMoneyInputDialog(int position) {
        MoneyDialog dialog = new MoneyDialog(TaskFromActivity.this, "金额", "确认", "取消");
        dialog.setHintMsg("请输入金额");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setClicklistener(new CustomDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                String money = dialog.getInputMsg();
                if (!money.equals("")) {
                    projectList.get(position).setAppMoney(Integer.valueOf(money));
                    projectList.get(position).setAuditMoney(Integer.valueOf(money));

                    applyMoney = Integer.valueOf(money);
                    int summoney = 0;
                    for (ProjectDetailDTO item : projectList) {
                        summoney += item.getAuditMoney();
                    }
                    applyMoney = summoney;
                    applyForDTO.setAppMoney(BigDecimal.valueOf(applyMoney));
                    applyforSumMoney.setText(String.valueOf(applyMoney));//本次申请

                    //applyforResignMoney.setText(String.valueOf(applyMoney));
                    applyForDTO.setAuditMoney(BigDecimal.valueOf(applyMoney));
                    adapter.notifyDataSetChanged();
                    showCauseInputDialog(position);
                    dialog.dismiss();
                }

            }

            @Override
            public void doCancel() {
                dialog.dismiss();
            }
        });
    }

    private void showCauseInputDialog(int position) {
        TextFieldDialog dialog = new TextFieldDialog(TaskFromActivity.this, "申请原因", "请输入申请原因", "确认", "取消");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setInputMsg(cause);
        dialog.setClicklistener(new CustomDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                cause = dialog.getInputMsg();
                if (!cause.equals("")) {
                    projectList.get(position).setAppReason(cause);
                    dialog.dismiss();
                }

            }

            @Override
            public void doCancel() {
                dialog.dismiss();
            }
        });
    }

    private void showInvoiceInputDialog() {
        CustomDialog dialog = new CustomDialog(TaskFromActivity.this, "发票", "是否有发票", "确认", "取消");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setClicklistener(new CustomDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                invoice = "是";
                saveAdult();
                dialog.dismiss();
            }

            @Override
            public void doCancel() {
                invoice = "否";
                saveAdult();
                dialog.dismiss();
            }
        });
    }

    public void saveAdult() {
        applyforFromProgressbar.setVisibility(View.VISIBLE);
        applyForDTO.setMainTicketId(Integer.valueOf(forkey));
        applyForDTO.setTyBusinessAppDetailVos(projectList);
        applyForDTO.setInvoice(invoice);
        int adultMoney = 0;
        for (ProjectDetailDTO item : projectList) {
            adultMoney += item.getAuditMoney();
        }
        applyForDTO.setAuditMoney(new BigDecimal(adultMoney));
        ProjectDTO projectDTO = new ProjectDTO();
        projectDTO.setId(applyForDTO.getId());
        projectDTO.setTheme(applyForDTO.getTheme());
        projectDTO.setNo(applyForDTO.getNo());
        projectDTO.setProcessInstanceId(applyForDTO.getProcessInstanceId());
        projectDTO.setProcessDefinitionId(applyForDTO.getProcessDefinitionId());
        projectDTO.setTaskId(applyForDTO.getTaskId());
        projectDTO.setExecutionId(applyForDTO.getExecutionId());
        projectDTO.setCurrentUserDepId(applyForDTO.getCurrentUserDepId());
        projectDTO.setHistoryUsernames(applyForDTO.getHistoryUsernames());
        projectDTO.setHistoryUserIds(applyForDTO.getHistoryUserIds());
        projectDTO.setProcessDefinitionKey(applyForDTO.getProcessDefinitionKey());
        projectDTO.setActivitiname(applyForDTO.getActivitiname());
        projectDTO.setStatus(applyForDTO.getStatus());
        projectDTO.setAppType(applyForDTO.getAppType());
        projectDTO.setAppReason((String) applyForDTO.getAppReason());
        projectDTO.setAppUserid(applyForDTO.getAppUserid());
        projectDTO.setAppUsertel(applyForDTO.getAppUsertel());
        projectDTO.setAppUserName(applyForDTO.getAppUserName());
        projectDTO.setAppDate(applyForDTO.getAppDate());
        projectDTO.setInvoice(applyForDTO.getInvoice());
        projectDTO.setVersion(applyForDTO.getVersion());
        projectDTO.setBusinessNo(applyForDTO.getBusinessNo());
        projectDTO.setAppMoney(applyForDTO.getAppMoney().doubleValue());
        projectDTO.setAppCompany(applyForDTO.getAppCompany());
        projectDTO.setAuditMoney(applyForDTO.getAuditMoney().doubleValue());
        projectDTO.setAppRegion(applyForDTO.getAppRegion());
        projectDTO.setAppCompanyId(applyForDTO.getAppCompanyId());
        projectDTO.setAppRegionId((Integer) applyForDTO.getAppRegionId());
        projectDTO.setRegionUserid(applyForDTO.getRegionUserid());
        projectDTO.setCenterUserid((String) applyForDTO.getCenterUserid());
        projectDTO.setSubCompanyManagerid(applyForDTO.getSubCompanyManagerid());
        projectDTO.setCompanyManagerid(applyForDTO.getCompanyManagerid());
        projectDTO.setAccounterid(applyForDTO.getAccounterid());
        projectDTO.setAccounterName(applyForDTO.getAccounterName());
        projectDTO.setAccoutFinalStatus((String) applyForDTO.getAccoutFinalStatus());
        projectDTO.setLimitMoney(applyForDTO.getLimitMoney());
        projectDTO.setTotalMoney(applyForDTO.getTotalMoney());
        projectDTO.setManagerAudit(applyForDTO.isManagerAudit());
        projectDTO.setLimitType(applyForDTO.getLimitType());
        projectDTO.setGzzUuid((String) applyForDTO.getIsGzzAudit());
        projectDTO.setGzzStatus(applyForDTO.getGzzStatus());
        projectDTO.setGzzUserName(applyForDTO.getGzzUserName());
        projectDTO.setAppDateStart(applyForDTO.getAppDateStart());
        projectDTO.setAppDateEnd(applyForDTO.getAppDateEnd());
        projectDTO.setTotalAuditMoney(applyForDTO.getTotalAuditMoney());

        projectDTO.setDtos(projectList);
        System.out.println("======" + projectDTO.toString());
        Call<BaseResp<Object>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).updateApplyForFetail("ANDROID", projectDTO);
        call.enqueue(new BaseCallBack<BaseResp<Object>>() {
            @Override
            public void onSuccess(Response<BaseResp<Object>> response) throws Exception {
                System.out.println("=======" + response.body().toString());
                String code = response.body().getCode();
                boolean success = response.body().getSuccess();
                if (code.equals("200") && success) {
                    Toast.makeText(TaskFromActivity.this, "重新提交成功", Toast.LENGTH_SHORT).show();
                    TaskFromActivity.this.finish();
                }
            }

            @Override
            public void onFailure(String message) {

            }
        });
    }


    private void setToolbar() {
        toolbar.setNavigationIcon(R.drawable.ic_left_black_24dp);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);


    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case android.R.id.home:
                this.finish();
                return true;

        }
        return super.onOptionsItemSelected(item);
    }

    private String getdivide(BigDecimal val1) {
        BigDecimal val2 = new BigDecimal(10000);
        BigDecimal decimal = val1.divide(val2);
        if (decimal.intValue() >= 1) {
            //方式一
            DecimalFormat df1 = new DecimalFormat("0.00");
            String str1 = df1.format(decimal.doubleValue());
            return str1 + "万根";
        } else {
            DecimalFormat df2 = new DecimalFormat("0.0");
            String str2 = df2.format(val1.doubleValue());
            return str2 + "根";
        }
    }

    @OnClick(R.id.applyfor_save_btn)
    public void onViewClicked() {
        saveAdult();
//        showInvoiceInputDialog();
    }
}
